/**
 * Mar 12, 2014 - 2:57:44 PM
 */
package elitech.vietnam.weatherfashion.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import elitech.vietnam.weatherfashion.R;

/**
 * @author Cong Vo
 *
 */
public class MaskImageView extends ImageView {

	Paint mPaint = null;
	Bitmap mMask = null;
	int maskResId = 0;

	public MaskImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setup(attrs);
	}

	public MaskImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setup(attrs);
	}

	public MaskImageView(Context context) {
		super(context);
		setup(null);
	}
	
	private void getAttrs(AttributeSet attrs) {
		if (attrs == null) 
			return;
		TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MaskImageView);
		maskResId = typedArray.getResourceId(R.styleable.MaskImageView_maskSrc, 0);
		typedArray.recycle();
	}

    private void setup(AttributeSet attrs) {
    	getAttrs(attrs);
        mPaint = new Paint();
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }
    
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (mMask != null)
			canvas.drawBitmap(mMask, 0, 0, mPaint);
	}
	
	@Override
	public void setImageDrawable(Drawable drawable) {
		super.setImageDrawable(drawable);
		if (maskResId != 0)
			mMask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), maskResId), getWidth(), getHeight(), false);
		invalidate();
	}
}
